﻿///初始化用户信息
var userinfo = (function () {
    return {
        UserId: "93661cd4-a563-4f64-94d7-73488af08ab1",
        UserName: "SomeOne"
    };
})();

//文章ID
var articleId = $("#hidArticleId").val();
//点赞锁标识
var praise_lock = 0;
//评论锁标识
var comment_lock = 0;

//滚动加载完成后的通用方法
function scrollLoadComplete(elementsLoaded) {

    //填充内容
    var pageIndex = parseInt($("#loadNext").attr("data-page"));
    var pageCount = parseInt($("#loadNext").attr("data-max"));
    var pageClassName = "club_page_" + pageIndex;
    var pageClass = "." + pageClassName;

    if (isNaN(pageIndex)) {
        pageClass = "";
        pageClassName = "";
    } else {
        $("#loadNext").hide();
        $("#loadNext").attr("data-page", pageIndex + 1);
        $("#allThreadList").append("<div class='" + pageClassName + "'></div>");
        $("#allThreadList " + pageClass).html(elementsLoaded);
    }

    //图片居中显示
    iUtility.ImageCenter(".slideBox", "li");

    //显示全文和收起
    $("#allThreadList " + pageClass + " .viewBtn").click(function (e) {
        var button = $(this);
        var content = $(this).parents(".detailCon").find(".contenttext");
        if (content.hasClass("contentbox")) {
            content.removeClass("contentbox");
            button.text("收起");
        } else {
            content.addClass("contentbox");
            button.text("全文");
        }
    });

    //全屏大图轮播
    $("#page-detail " + pageClass + " .slideBox li").click(function (e) {

        //添加轮播dom结构
        if ($("#fullScreenSlides").length == 0) {
            $(document.body).append(
                '<div id="fullScreenSlides" class="fssBox" style="display: none;">' +
                '    <div class="fssWrapper"></div>' +
                '    <div class="fssPagination"></div>' +
                '</div>'
            );
        }
        var thumbSrc = $(this).find("img").attr("src");
        var index = parseInt($(this).attr("data-count"));
        var slidesHTML = "";
        $(this).parents(".slideContainer").find("li").each(function () {
            var imgsrc = $(this).find("img").attr("src");
            var bigsrc = $(this).find("img").attr("data-big");
            slidesHTML += '<div class="fssImage"><img alt="" src="' + imgsrc + '" data-big="' + bigsrc + '" /></div>';
        });
        $("#fullScreenSlides .fssWrapper").html(slidesHTML);
        $("#fullScreenSlides .fssWrapper .fssImage").width(document.documentElement.clientWidth);
        $("#fullScreenSlides .fssWrapper .fssImage").height(document.documentElement.clientHeight);

        //初始化轮播组件
        var mySwiper = new Swiper("#fullScreenSlides", {
            autoplay: false,
            mode: "horizontal",
            wrapperClass: "fssWrapper",
            createPagination: true,
            pagination: ".fssPagination",
            paginationElementClass: "page",
            paginationActiveClass: "current",
            paginationAsRange: false,
            paginationClickable: true,
            slideClass: "fssImage",
            slideActiveClass: "slideActive",
            watchActiveIndex: true,
            centeredSlides: true,
            onInit: function (swiper) {
                swiper.swipeTo(index, 0);
                var current = $(swiper.getSlide(index)).find("img");
                current.attr("src", current.attr("data-big"));
            },
            onImagesReady: function () {
                $("#fullScreenSlides .fssPagination .page:eq(" + index + ")").addClass("current");
                $("#fullScreenSlides").show();
            },
            onSlideClick: function (swiper) {
                swiper.destroy();
                $("#fullScreenSlides").hide();
                $("#fullScreenSlides .fssWrapper").empty();
                iUtility.RemoveShade();
            },
            onSlideChangeStart: function (swiper, direction) {
                var current = $(swiper.activeSlide()).find("img");
                if (!current.hasClass("IsSource")) {
                    current.attr("src", current.attr("data-big"));
                    current.addClass("IsSource");
                }
            }
        });

        //添加遮罩层
        iUtility.AppendShade({ opacity: 0.9 });
        $("#fullScreenSlides").show();

    });

    //评论
    $("#allThreadList " + pageClass + " .threadReply").click(openReplyForm);

    if (pageIndex >= pageCount) {
        $("#allThreadList").stopScrollPagination();
        $("#loadNext").text("");
    }

    $("#allThreadList " + pageClass + " .more").click(function () {
        window.location.href = "/club/detail/" + $(this).attr("data-pid");
    });

    $("#allThreadList " + pageClass + " .threadDelete").click(function () {
        if (confirm("确定删除此评论？")) {
            var postID = $(this).attr("data-pid");
            var commentID = $(this).attr("data-cid");
            ClubAction.DeleteComment(postID, commentID, 0, function () {
                $("#comment" + commentID).remove();
                checkReplyListVisible(postID);
            });
        }
    });

    //点赞
    $("#allThreadList " + pageClass + " .like").click(function (e) {
        var p = $(this);
        if (p.attr("data-praised") == 0) {
            var postID = p.attr("data-pid");
            var userID = p.attr("data-uid");
            var userName = p.attr("data-uname");
            var icon = p.find("i");
            ClubAction.Praise(postID, userID, userName, function (objInvokeResult) {
                if (objInvokeResult.ResultCode == "Success") {
                    p.attr("data-praised", 1);
                    p.find(".num").text(parseInt(p.text()) + 1);
                    icon.removeClass("noPraise");
                    icon.addClass("praise");
                }
            });
        }
        e.stopPropagation();
    });
    
    $("#page-list " + pageClass + " .detailCon").click(function (e) {
        var target = $(e.target);
        if (!target.hasClass("like") && !target.hasClass("threadReply")) {
            //window.location.href = "detail.html";
        }
        e.stopPropagation();
    });
}
//打开评论窗口
function openReplyForm(e) {
    var postID = parseInt($(this).attr("data-pid"));
    var userID = parseInt($(this).attr("data-uid"));
    var userName = $(this).attr("data-username");
    var IsReply = $(this).attr("data-reply") == 0 ? 0 : 1;
    //添加遮罩层
    iUtility.AppendShade({ opacity: 0.5 });
    //添加评论窗口dom
    if ($("#fwin_dialog_replyForm").length == 0) {
        //var textHolder = userName == "" ? "评论：" : "回复 " + userName + "：";
        var textHolder = "发表评论";
        var inputValue = "@" + userName + " ";
        $(document.body).append(
            '<div id="fwin_dialog_replyForm" style="width: 100%; position: fixed; z-index: 10001; top: 50px; left: 0px;">' +
            '    <div style="width:auto" class="popLayer brSmall">' +
            '        <div class="sendBorder">' +
            '           <textarea placeholder="' + textHolder + '" class="sInput1" rows="" cols="" name="content" id="content"></textarea>' +
            '        </div>' +
            '        <div class="sendOperate">' +
            '            <a title="" class="expreSelect cf" href="javascript:;"></a>' +
            '            <div class="operBtn fr">' +
            '                <span id="pText" class="pText" style="display:none;">140</span>' +
            '                <a title="" class="cancelBtn db close" id="cBtn" href="javascript:;">取消</a>' +
            '                <a title="" class="sendBtn1 c1 db" id="comBtn" href="javascript:;">发送</a>' +
            '            </div>' +
            '        </div>' +
            '    </div>' +
            '    <div id="emotion" data-part="emotion" style="display:none;"><div class="expreList"><div class="expressionTab"><a title="默认"id="emo0"class="on"href="javascript:;">默认</a></div><div class="expreBox"><ul style=""id="exp_emo0"class="expreCon expreConNew"><li class="slide slide-visible bg1"style="background-position: center center;"><a title="微笑"href="javascript:;"></a><a title="撇嘴"href="javascript:;"></a><a title="色"href="javascript:;"></a><a title="发呆"href="javascript:;"></a><a title="得意"href="javascript:;"></a><a title="流泪"href="javascript:;"></a><a title="害羞"href="javascript:;"></a><a title="闭嘴"href="javascript:;"></a><a title="睡"href="javascript:;"></a><a title="大哭"href="javascript:;"class=""></a><a title="尴尬"href="javascript:;"></a><a title="发怒"href="javascript:;"></a><a title="调皮"href="javascript:;"></a><a title="呲牙"href="javascript:;"></a><a title="惊讶"href="javascript:;"></a><a title="难过"href="javascript:;"></a><a title="酷"href="javascript:;"></a><a title="冷汗"href="javascript:;"></a><a title="抓狂"href="javascript:;"></a><a title="吐"href="javascript:;"></a><a href="javascript:;"class=""></a></li><li class="slide bg2"style="background-position: center center;"><a title="偷笑"href="javascript:;"></a><a title="可爱"href="javascript:;"></a><a title="白眼"href="javascript:;"></a><a title="傲慢"href="javascript:;"></a><a title="饥饿"href="javascript:;"></a><a title="困"href="javascript:;"></a><a title="惊恐"href="javascript:;"></a><a title="流汗"href="javascript:;"></a><a title="憨笑"href="javascript:;"></a><a title="大兵"href="javascript:;"></a><a title="奋斗"href="javascript:;"></a><a title="咒骂"href="javascript:;"></a><a title="疑问"href="javascript:;"></a><a title="嘘.."href="javascript:;"></a><a title="晕"href="javascript:;"></a><a title="折磨"href="javascript:;"></a><a title="衰"href="javascript:;"></a><a title="骷髅"href="javascript:;"></a><a title="敲打"href="javascript:;"></a><a title="再见"href="javascript:;"></a><a href="javascript:;"></a></li><li class="slide bg3"style="background-position: center center;"><a title="擦汗"href="javascript:;"></a><a title="抠鼻"href="javascript:;"></a><a title="鼓掌"href="javascript:;"></a><a title="溴大了"href="javascript:;"></a><a title="坏笑"href="javascript:;"></a><a title="左哼哼"href="javascript:;"></a><a title="右哼哼"href="javascript:;"></a><a title="哈欠"href="javascript:;"></a><a title="鄙视"href="javascript:;"></a><a title="委屈"href="javascript:;"></a><a title="快哭了"href="javascript:;"></a><a title="阴险"href="javascript:;"></a><a title="亲亲"href="javascript:;"></a><a title="吓"href="javascript:;"></a><a title="可怜"href="javascript:;"></a><a title="菜刀"href="javascript:;"></a><a title="西瓜"href="javascript:;"></a><a title="啤酒"href="javascript:;"></a><a title="篮球"href="javascript:;"></a><a title="乒乓"href="javascript:;"></a><a href="javascript:;"></a></li><li class="slide bg4"style="background-position: center center;"><a title="咖啡"href="javascript:;"></a><a title="饭"href="javascript:;"></a><a title="猪头"href="javascript:;"></a><a title="玫瑰"href="javascript:;"></a><a title="凋谢"href="javascript:;"></a><a title="示爱"href="javascript:;"></a><a title="爱心"href="javascript:;"></a><a title="心碎"href="javascript:;"></a><a title="蛋糕"href="javascript:;"></a><a title="闪电"href="javascript:;"></a><a title="炸弹"href="javascript:;"></a><a title="刀"href="javascript:;"></a><a title="足球"href="javascript:;"></a><a title="瓢虫"href="javascript:;"></a><a title="便便"href="javascript:;"></a><a title="月亮"href="javascript:;"></a><a title="太阳"href="javascript:;"></a><a title="礼物"href="javascript:;"></a><a title="拥抱"href="javascript:;"></a><a title="强"href="javascript:;"></a><a href="javascript:;"></a></li><li class="slide bg5"style="background-position: center center;"><a title="弱"href="javascript:;"></a><a title="握手"href="javascript:;"></a><a title="胜利"href="javascript:;"></a><a title="抱拳"href="javascript:;"></a><a title="勾引"href="javascript:;"></a><a title="拳头"href="javascript:;"></a><a title="差劲"href="javascript:;"></a><a title="爱你"href="javascript:;"></a><a title="NO"href="javascript:;"></a><a title="OK"href="javascript:;"></a><a title="爱情"href="javascript:;"></a><a title="飞吻"href="javascript:;"></a><a title="跳跳"href="javascript:;"></a><a title="发抖"href="javascript:;"></a><a title="怄火"href="javascript:;"></a><a title="转圈"href="javascript:;"></a><a title="磕头"href="javascript:;"></a><a title="回头"href="javascript:;"></a><a title="跳绳"href="javascript:;"></a><a title="挥手"href="javascript:;"></a><a href="javascript:;"></a></li></ul></div><p id="exp_emo0_page"class="pNumCon"><a class="pNumOn pNum db"href="javascript:;"></a><a class="pNum db"href="javascript:;"></a><a class="pNum db"href="javascript:;"></a><a class="pNum db"href="javascript:;"></a><a class="pNum db"href="javascript:;"></a></p></div></div>' +
            '</div>'
        );
    }
    //评论内容框获得焦点，弹出键盘
    $("#content").focus();
    if (IsReply) {
        $("#content").val(inputValue);
    }
    //滑动绑定
    var mySwiper = new Swiper(".expreBox", {
        mode: "horizontal",
        wrapperClass: "expreCon",
        initialSlide: 0,
        createPagination: false,
        pagination: ".pNumCon",
        paginationElementClass: "pNum",
        paginationActiveClass: "pNumOn",
        paginationVisibleClass: "pNumOn",
        paginationClickable: true,
        paginationAsRange: false,
        slideClass: "slide",
        slideActiveClass: "slide-visible",
        slideVisibleClass: "slide-visible"
    });
    //点击表情图标显示表情列表操作
    $("#fwin_dialog_replyForm .expreSelect").click(function () {
        if ($("#emotion").is(":hidden")) {
            $("#emotion").show();
        } else {
            $("#emotion").hide();
        }
    });
    //选择表情
    $("#exp_emo0 a").click(function (e) {
        var textbox = $("#content");
        var emotion = $(this).attr("title");
        if (emotion == undefined || emotion == "") {
            textbox.val(textbox.val().replace(/\[[^\]]*\]$/, ""));
        } else {
            textbox.val(textbox.val() + "[" + emotion + "]");
        }
        e.stopPropagation();
    });
    //关闭评论窗口
    $("#fwin_dialog_replyForm #cBtn").click(function () {
        closeReplyForm();
    });
    //绑定发表评论操作
    bindCommentAction(postID, IsReply);

    e.stopPropagation();
}
//关闭评论窗口
function closeReplyForm() {
    $("#fwin_dialog_replyForm").remove();
    iUtility.RemoveShade();
}
//处理@xxx
function formatAtSign() {
    var _this = $(this).find(".comcon");
    var comment = _this.text();
    var commentID = _this.parents("li").attr("data-cid");
    comment = comment.replace(/@([^\s|<]+)/g, "<a href='javascript:;' class='threadReply' data-cid='" + commentID + "' data-pid='" + articleId + "' data-username='$1'>@$1</a>");
    _this.html(comment);
}
//检查评论列表可见性
function checkReplyListVisible(postID) {
    var replyBox = $("#rlist" + postID).parents(".replyBox");
    if ($("#rlist" + postID + " li").length == 0) {
        replyBox.hide();
    }
}

/*
 =========================================================
 */

//获取最新评论
function getLatestComment(commentID, success) {
    var action = "/guangqi/commenttoplist";
    var data = { CommentID: commentID, ID: articleId };
    getCommentList(action, data, success);
}
//获取历史评论
function getHistoryComment(commentID, success) {
    var action = "/guangqi/commentbottomlist";
    var data = { CommentID: commentID, ID: articleId };
    getCommentList(action, data, success);
}
//获取最热评论
function getHotComment(pageIndex, success) {
    var action = "/guangqi/commenthotlist";
    var data = { Page: pageIndex, ID: articleId };
    getCommentList(action, data, success);
}
//获取评论列表
function getCommentList(action, jsonData, success) {
    var defaultData = { Action: action };
    $.extend(defaultData, jsonData)
    $.ajax({
        type: 'GET',
        url: action,
        data: defaultData,
        dataType: "html",
        success: function (html) {
            if (action == "/guangqi/commenttoplist") {
                $("#commentList").prepend(html);
            } else {
                $("#commentList").append(html);
            }
            if ($("#commentList li").length >= 10) {
                $("#more_comment").show();
            }
            replaceCommentEmotion();
            bindCommentListAction();
            if (typeof (success) != "undefined") {
                success(html);
            }
        }
    })
}
//替换评论表情占位符为图片
function replaceCommentEmotion(list) {
    if (typeof (list) == "undefined") {
        list = $("#commentList li[data-action='unbind']");
    }
    list.find(".comcon").each(function () {
        var _this = $(this);
        _this.text(Emotion.Replace(_this.text()));
    });
}
//绑定评论列表操作
function bindCommentListAction(list) {
    if (typeof (list) == "undefined") {
        list = $("#commentList li[data-action='unbind']");
    }
    list.each(formatAtSign);
    list.find(".threadReply").click(openReplyForm);
    list.find(".noPraise").parents(".like").click(praise);
    //list.find(".like").click(praise);
    list.removeAttr("data-action");
}
//轮询是否有新评论
function rollPollingFunction() {
    var commentID = $("#commentList li:first").attr("data-cid");
    $.ajax({
        type: 'POST',
        url: "/guangqi/commentlast",
        data: { id: articleId, commentID: commentID },
        dataType: "JSON",
        success: function (result) {
            //result = { ResultCode: "Success", ResultMessage: "点赞成功！" }; //测试数据
            if (result.ResultCode == "Success") {
                $("#notify").show();
                closeRollPolling();
            }
        }
    })
}
//开启轮询
function startRollPolling() {
    ClubAction.IntervalID = setInterval(rollPollingFunction, 5000);
}
//停止轮询
function closeRollPolling() {
    clearInterval(ClubAction.IntervalID);
    ClubAction.IntervalID = undefined;
}
//点赞操作
function praise() {

    if (praise_lock == 1) return;
    praise_lock = 1;

    var _this = $(this);
    var commentID = _this.parents("li").attr("data-cid");
    $.ajax({
        type: 'post',
        url: "/guangqi/diggcomment",
        data: { id: commentID, articleId: articleId },
        dataType: "JSON",
        success: function (data) {
            //result = { ResultCode: "Success", ResultMessage: "点赞成功！" }; //测试数据

            praise_lock = 0;

            if (data.ResultCode == "Success") {
                var praiseCount = parseInt(_this.find(".num").text());
                _this.find(".num").text(praiseCount + 1);
            } else {
                alert(data.ResultMessage);
            }
            _this.find("i").removeClass("noPraise").addClass("praise");
            _this.off("click");
        }
    })
}
//发表评论操作
function bindCommentAction(postID, IsReply) {
    //发表评论操作点击事件
    $("#fwin_dialog_replyForm #comBtn").click(function () {

        if (comment_lock == 1) return;
        comment_lock = 1;

        var content = $("#content").val();
        if (!/[^\s]+/.test(content)) {
            alert("评论内容不能为空");
            $("#content").focus();
            return;
        }
        ClubAction.AddComment(postID, "", "", content, IsReply, function (objResultInfo) {
            if (objResultInfo.ResultCode == "Success") {
                var commentID = $("#commentList li:first").attr("data-cid");
                var userID = $("#hidCurrentUserID").val();
                var userName = $("#hidCurrentUserName").val();
                var node = $("#divCommentInfo").html().replace(/{CommentID}/g, objResultInfo.Data).replace(/{UserID}/g, userID).replace(/{UserName}/g, userName).replace(/{ArticleID}/g, articleId).replace(/{Content}/g, content);
                $("#commentList").prepend(node);
                var list = $("#comment" + objResultInfo.Data);
                replaceCommentEmotion(list);
                bindCommentListAction(list);
                closeReplyForm();
            }
            alert(objResultInfo.ResultMessage);

            comment_lock = 0;
        });
    });
}